package com.example.myjavaapp.slice;

import com.example.myjavaapp.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
import ohos.data.DatabaseHelper;
import ohos.data.rdb.*;
import ohos.data.resultset.ResultSet;

public class LoginAbilitySlice extends AbilitySlice {

    private Context context;
    private TextField userName;
    private TextField passWord;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_login);

        userName = (TextField) findComponentById(ResourceTable.Id_text_field1);
        passWord = (TextField) findComponentById(ResourceTable.Id_text_field2);
        context = getContext();
        Button btnRegister = (Button) findComponentById(ResourceTable.Id_button1);
        Button btnLogin = (Button) findComponentById(ResourceTable.Id_button2);

        if (btnRegister != null) {
            // 为按钮设置点击回调
            btnRegister.setClickedListener(component -> btnRegister());
        }

        if (btnLogin != null) {
            // 为按钮设置点击回调
            btnLogin.setClickedListener(component -> btnLogin());
        }
    }

    private void btnRegister(){

        String username = userName.getText();
        String password = passWord.getText();
        Text userErr=(Text) findComponentById(ResourceTable.Id_error_tip_text1);
        Text passErr=(Text) findComponentById(ResourceTable.Id_error_tip_text2);
        StoreConfig config = StoreConfig.newDefaultConfig("RdbStoreTest.db");
        RdbOpenCallback callback = new RdbOpenCallback() {
            @Override
            public void onCreate(RdbStore store) {
                store.executeSql("CREATE TABLE IF NOT EXISTS users (username TEXT, password Text)");
            }
            @Override
            public void onUpgrade(RdbStore store, int oldVersion, int newVersion) {
            }
        };
        DatabaseHelper helper = new DatabaseHelper(context);
        RdbStore store = helper.getRdbStore(config, 1, callback, null);

        ValuesBucket values = new ValuesBucket();

        //在实际应用中需要用安全的加密算法对用户注册密码进行加密处理。
        values.putString("username", username);
        values.putString("password",password);


        String regExp = "^[A-Za-z0-9]{1,20}$";
        if("".equals(username)||"".equals(password)||password.isEmpty()||username.isEmpty()){
            new ToastDialog(context).setText("请输入用户名和密码进行注册").show();
        }else{
            if(username.matches(regExp)){
                userErr.setVisibility(Component.HIDE);
                if(password.matches(regExp)){
                    passErr.setVisibility(Component.HIDE);
                    store.insert("users", values);
                    new ToastDialog(context).setText("注册成功！").show();
                }else{
                    passErr.setVisibility(Component.VISIBLE);
                }
            }else{
                userErr.setVisibility(Component.VISIBLE);

            }

        }
    }

    private void btnLogin() {
        String username = userName.getText();
        String password = passWord.getText();

        StoreConfig config = StoreConfig.newDefaultConfig("RdbStoreTest.db");
        RdbOpenCallback callback = new RdbOpenCallback() {
            @Override
            public void onCreate(RdbStore store) {
                store.executeSql("CREATE TABLE IF NOT EXISTS users (username TEXT, password Text)");
            }
            @Override
            public void onUpgrade(RdbStore store, int oldVersion, int newVersion) {
            }
        };
        DatabaseHelper helper = new DatabaseHelper(context);
        RdbStore store = helper.getRdbStore(config, 1, callback, null);

        String[] columns = new String[] {"username", "password"};
        RdbPredicates rdbPredicates = new RdbPredicates("users").equalTo("username", username).equalTo("password", password).orderByAsc("username");
        ResultSet resultSet = store.query(rdbPredicates, columns);
        if (resultSet == null || resultSet.getRowCount() == 0) {
            new ToastDialog(context).setText("用户名或密码错误。").show();
            return;
        }
        resultSet.goToFirstRow();
        if(resultSet !=null){
            Intent secondIntent = new Intent();
            // 指定待启动FA的bundleName和abilityName
            Operation operation = new Intent.OperationBuilder()
                    .withDeviceId("")
                    .withBundleName("com.example.myjavaapp")
                    .withAbilityName("com.example.myjavaapp.HomeAbility")
                    .build();
            secondIntent.setOperation(operation);
            // 通过AbilitySlice的startAbility接口实现启动另一个页面
            startAbility(secondIntent);
        }
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
